﻿using Artizan.Iot.Hub.Mqtt.AspNetCore.Servser;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet.AspNetCore;


namespace Artizan.Iot.Hub.Mqtt.AspNetCore.Extensions
{
    public static class IotHubMqttServerExtensions
    {
        /// <summary>
        /// MQTTnet 集成 AspNetCore：
        ///    https://github.com/dotnet/MQTTnet/wiki/Server#validating-mqtt-clients
        /// </summary>
        public static void AddIotHubMqttServer(this IServiceCollection services,
            Action<AspNetMqttServerOptionsBuilder> configure)
        {
            services.AddHostedMqttServerWithServices(builder =>
            {
                configure(builder);
            });
            services.AddMqttConnectionHandler();
            services.AddConnections();
        }

        public static void UseIotHubMqttServer(this IApplicationBuilder app)
        {
            app.UseMqttServer(mqttServer =>
            {
                app.ApplicationServices.GetRequiredService<IIotHubMqttServer>()
                  .ConfigureMqttServer(mqttServer);
            });

            app.UseEndpoints(endpoint =>
            {
                // endpoint.MapMqtt("/mqtt");
                endpoint.MapConnectionHandler<MqttConnectionHandler>(
                    "/mqtt", // 设置MQTT的访问地址: localhost:端口/mqtt
                    httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                        protocolList => protocolList.FirstOrDefault() ?? string.Empty); // MQTT 支持 HTTP WebSockets
            });
        }
    }
}
